package com.whcoding.designpatterns.pattern.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: spring-boot-learning
 * @description: 动态处理类
 * @author: whcoding
 * @create: 2022-09-21 10:32
 **/
public class DynamicProxyFactory implements MethodInterceptor {

	private Object target;

	public DynamicProxyFactory(Object target) {
		this.target = target;
	}


	/**
	 * 返回代理对象
	 *
	 * @return
	 */
	public Object getProxyInstance() {
		// 创建一个工具类
		Enhancer enhancer = new Enhancer();
		// 设置父类
		enhancer.setSuperclass(target.getClass());
		// 设置回调函数
		enhancer.setCallback(this);
		// 返回代理对象
		return enhancer.create();
	}


	/**
	 * 重写intercept方法，调用目标方法
	 *
	 * @param o
	 * @param method
	 * @param objects
	 * @param methodProxy
	 * @return
	 * @throws Throwable
	 */
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		System.out.println("cglib代理模式开始前的方法。。。。");
		Object invoke = method.invoke(target, objects);
		System.out.println("cglib代理模式结束后的方法。。。。");
		return invoke;
	}
}
